package pri.hillchen.std.simpledemo.javaapi;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 8:53 2018/3/12 0012.
 */
public class SimpleDemo {
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper("localhost:2181",15000,(WatchedEvent watchedEvent) -> {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                // 放开闸门, wait在connect方法上的线程将被唤醒
                System.out.println("连接zookeeper成功");
                countDownLatch.countDown();
            }else{
                // 放开闸门, wait在connect方法上的线程将被唤醒
                System.out.println("连接zookeeper异常");
            }

        });
        countDownLatch.await();


        for(int i=0;i<10;i++){
            createZNode(zooKeeper,"/simpleDemo"+i,("/simpleDemo"+i).getBytes());
        }

        System.in.read();

    }

    private static void createZNode(ZooKeeper zooKeeper,String path,byte[] data) throws KeeperException, InterruptedException {
        CountDownLatch childeEventLatch = new CountDownLatch(1);
        zooKeeper.getChildren("/",(WatchedEvent watchedEvent) -> {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                // 放开闸门, wait在connect方法上的线程将被唤醒
                System.out.println("创建子节点成功:"+watchedEvent.getPath());
                childeEventLatch.countDown();
            }
        });
        zooKeeper.create(path,data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        childeEventLatch.await();
    }
}
